package com.example.chapter06;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class DatabaseActivity extends AppCompatActivity implements View.OnClickListener {

    private String mDatabaseName;
    private TextView tv_database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_database);
        findViewById(R.id.btn_database_create).setOnClickListener(this);
        findViewById(R.id.btn_database_delete).setOnClickListener(this);
        tv_database = findViewById(R.id.tv_database);

        //生成一个测试数据库的完整路径
        mDatabaseName = getFilesDir() + "/test.db";
    }

    @Override
    public void onClick(View view) {
        String desc = null;
        if (view.getId() == R.id.btn_database_create) {
            //创建或者打开数据库。数据库如果不存在就创建，如果存在就打开
            SQLiteDatabase db = openOrCreateDatabase(mDatabaseName, Context.MODE_PRIVATE, null);
            desc = String.format("数据库%s创建%s", db.getPath(), "成功");
            tv_database.setText(desc);
        }
        if (view.getId() == R.id.btn_database_delete) {
            boolean b = deleteDatabase(mDatabaseName);
            desc = String.format("数据库%s删除%s", mDatabaseName, b ? "成功" : "失败");
            tv_database.setText(desc);
        }
    }
}